class Cpanel::ProductsController < Cpanel::BaseController
  before_action :set_product, only: [:show, :edit, :update, :destroy]

  def index
    respond_to do |format|
      format.html
      format.json { render json: ProductsDatatable.new(view_context, current_admin) }
    end
  end

  def show; end

  def new
    @product = Product.new
  end

  def edit; end

  def create
    @product = Product.new(product_params)

    respond_to do |format|
      if @product.save
        format.html { redirect_to cpanel_product_path(@product), notice: '商品创建成功' }
        format.json { render :show, status: :created, location: @product }
      else
        format.html { render :new }
        format.json { render json: @product.errors, status: :unprocessable_entity }
      end
    end
  end

  def update
    respond_to do |format|
      if @product.update(product_params)
        format.html { redirect_to cpanel_product_path(@product), notice: '商品更新成功' }
        format.json { render :show, status: :ok, location: @product }
      else
        format.html { render :edit }
        format.json { render json: @product.errors, status: :unprocessable_entity }
      end
    end
  end

  def destroy
    @product.destroy
    render js: 'CPANEL.Products.DataTable.refresh();CPANEL.alert_success("删除成功");'
  end

  def modal
    respond_to do |format|
      format.html
      format.json { render json: ProductsModalDatatable.new(view_context, current_admin) }
    end
  end

  private

  # Use callbacks to share common setup or constraints between actions.
  def set_product
    @product = Product.find(params[:id])
  end

  # Never trust parameters from the scary internet, only allow the white list through.
  def product_params
    params.require(:product).permit(:name, :price, :avatar_q_key, :avatar_q_bucket, :memo)
  end
end
